package WaitNotify;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UseWaitAndNotify {
    static final Object  room = new Object();
    static boolean hasCigarette = false;//有没有烟
    static boolean hasTakeout = false;//有没有外卖

    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            synchronized (room) {
                log.debug("有烟没？[{}]",hasCigarette);
                if(!hasCigarette){
                    log.debug("没烟，先歇会！");
                    try {
//                        Thread.sleep(2000);
                        room.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                log.debug("有烟没？[{}]", hasCigarette);
                if (hasCigarette) {
                    log.debug("可以开始干活了");
                }
            }
        },"小南").start();

        for(int i= 0;i<5;i++){
            new Thread(()->{
                synchronized (room) {
                    log.debug("可以开始干活了");
                }
            },"其他人").start();
        }

        Thread.sleep(1000);
        new Thread(()->{
            //如果是小南用sleep方法，这里加synchronized是没意义的，因为小南独占room
            synchronized (room) {
                hasCigarette = true;
                log.debug("烟到了噢！");
                room.notifyAll();
            }
        },"送烟的").start();
    }
}
